package com.easyfun.healthmagicbox.auth;

import java.sql.SQLException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.easyfun.healthmagicbox.HMBMainActivity;
import com.easyfun.healthmagicbox.R;
import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.comm.PersonProfileUploadTask;
import com.easyfun.healthmagicbox.comm.PersonQuestionsUploadTask;
import com.easyfun.healthmagicbox.comm.UserLoginTask;
import com.easyfun.healthmagicbox.comm.UserRegisterTask;
import com.easyfun.healthmagicbox.comm.UserToPersonsUpTask;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.PersonProfile;
import com.easyfun.healthmagicbox.pojo.User;
import com.easyfun.healthmagicbox.pojo.UserToPersons;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.easyfun.healthmagicbox.util.ImageTools;
import com.easyfun.healthmagicbox.util.PersonProfileCache;
import com.easyfun.healthmagicbox.util.URIConverter;
import com.j256.ormlite.dao.Dao;

public class RegisterActivity extends BaseActivity implements DatabaseAccess{
	
	String page1_login_user_edit ;
	String page1_login_passwd_edit;
	String page1_login_passwd_edit2;

	String page1_login_email_edit;

	String page1_login_phone_edit;
	protected final static String LOG_TAG = RegisterActivity.class.getSimpleName();
	
	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pageregister);
		//addbackButton should after setting content view
				addbackButton(this);
				
		Button loginbut = (Button) findViewById(R.id.page1_login_but);
		loginbut.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
				intent.putExtra(ConstantData.HMBUSERNAME,page1_login_user_edit);
				RegisterActivity.this.startActivity(intent);
			}
		});
		
		Button regbut = (Button) findViewById(R.id.page1_regist_but);
		regbut.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!verifyReg()) return;
				User user=new User();
				user.setEmail(page1_login_email_edit);
				user.setPassword(page1_login_passwd_edit);
				user.setUsername(page1_login_user_edit);
				user.setPhonenum(page1_login_phone_edit);
				user.setPersonID(PersonProfileCache.generatePersonID(RegisterActivity.this));
				CommCallback ccb = new BasicCommCallback();
				UserRegisterTask regtask = new UserRegisterTask(RegisterActivity.this, user, ccb);
				HealthThreadPool.getInstance().execute(regtask);
				String responseValue = "";
				int i = 0;
				ServerResponseCode src = ccb.getCommResult(UserRegisterTask.class, responseValue);
				while ((src==ServerResponseCode.WAITING) && (i<100))
				{
					synchronized (ccb) {
						try {
							ccb.wait(100);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					src = ccb.getCommResult(UserLoginTask.class, responseValue);
					i++;
				}
				
				if (src == ServerResponseCode.NOMORE)
				{
					Toast.makeText(getApplicationContext(),
							"用户名太好，已经有人用了！",
							Toast.LENGTH_SHORT).show();
					return;
				}else if (src == ServerResponseCode.FAILED)
				{
					Toast.makeText(getApplicationContext(),
							"注册失败，请与客服联系！",
							Toast.LENGTH_SHORT).show();
				}else if (src == ServerResponseCode.SUCCESS)
				{
					try {

						Dao<User, Integer> dao = getHelper(RegisterActivity.this)
								.getUserDao();
						dao.create(user);
						
						Dao<UserToPersons, Integer> utopDao = 
								getHelper(RegisterActivity.this).getUserToPersonsDao();
						UserToPersons data = new UserToPersons();
						data.setPersonID(user.getPersonID());
						data.setUsername(user.getUsername());
						data.setRetitle("自己");
						utopDao.create(data);
						
						//BUG 3:
						UserToPersonsUpTask task2 = new UserToPersonsUpTask(
							user.getUsername(), 
							user.getPersonID(), 
							"自己","",
							RegisterActivity.this,
							new BasicCommCallback());
						
						HealthThreadPool.getInstance().execute(task2);
						
						Dao<PersonProfile, Integer> ppDao = 
								getHelper(RegisterActivity.this).getPersonProfileDao();
						
						PersonProfile pp = new PersonProfile();
						pp.setPersonID(user.getPersonID());
						pp.setName("老大");
						pp.setWeigth(0.0);
						pp.setHeigth(0.0);
						pp.setSharelist("");
						pp.setInvitedCode("0");
						pp.setManualinput(ConstantData.ManualInputNo);
						
						pp.setImageFileName(ConstantData.DEFAULT_HEAD_ICON_MALE);
						/*
						Bitmap bitmap = ImageTools.createTextBitmap(RegisterActivity.this, 100, 160, 6, 5, 
								5,pp.getTitle(), pp.getName());
						if (bitmap != null){
							URIConverter.savePhotoToAppSDCard(bitmap, user.getPersonID()+".png");
							pp.setImageFileName(user.getPersonID()+".png");
						}
						else
							Log.e(LOG_TAG ,"can't dynamically create an head image.");
						*/
						ppDao.create(pp);
						
						//upload main person
						PersonProfileUploadTask task = new PersonProfileUploadTask(RegisterActivity.this, 
								user.getPersonID(),new BasicCommCallback() );
						HealthThreadPool.getInstance().execute(task);
						Toast.makeText(getApplicationContext(),
								"注册成功，请返回登陆。",
								Toast.LENGTH_SHORT).show();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}else
				{
					Toast.makeText(getApplicationContext(),
							"服务器连接，请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
					
			}
		});
	}
	
	protected boolean verifyReg()
	{
		page1_login_user_edit = ((TextView) 
				findViewById(R.id.page1_login_user_edit)).getText().toString();
		page1_login_passwd_edit = ((TextView) 
				findViewById(R.id.page1_login_passwd_edit)).getText().toString();
		page1_login_passwd_edit2 =  ((TextView) 
				findViewById(R.id.page1_login_passwd_edit2)).getText().toString();

		page1_login_email_edit =  ((TextView) 
				findViewById(R.id.page1_login_email_edit)).getText().toString();

		page1_login_phone_edit =  ((TextView) 
				findViewById(R.id.page1_login_phone_edit)).getText().toString();
		if ((page1_login_user_edit==null)||(page1_login_user_edit.length()==0))
		{
			Toast.makeText(getApplicationContext(),
					"用户名不能为空",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		if ((page1_login_passwd_edit==null)||(page1_login_passwd_edit.length()==0)||
				(page1_login_passwd_edit2==null)||(page1_login_passwd_edit2.length()==0))
		{
			Toast.makeText(getApplicationContext(),
					"密码不能为空",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		if (!(page1_login_passwd_edit.equals(page1_login_passwd_edit2)))
		{
			Toast.makeText(getApplicationContext(),
					"密码不相同",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		if (page1_login_passwd_edit.length()<6)
		{
			Toast.makeText(getApplicationContext(),
					"密码至少六位！",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		if ((page1_login_email_edit==null)||(page1_login_email_edit.length()==0))
		{
			Toast.makeText(getApplicationContext(),
					"电子邮件必须填写",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		
		if ((page1_login_email_edit.indexOf('@')<0)||(page1_login_email_edit.indexOf('.')<0))
		{
			Toast.makeText(getApplicationContext(),
					"电子邮件必须填写正确，格式必须是xxx@xxx.xxx",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		if ((page1_login_phone_edit==null)||(page1_login_phone_edit.length()<11))
		{
			Toast.makeText(getApplicationContext(),
					"手机号位数不够，至少11位",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
}
